﻿#include "cameraworker.h"
#include <QThread>
CameraWorker::CameraWorker(QObject *parent) : QObject(parent)
{
    m_bIsStreaming = false;
}

CameraWorker::~CameraWorker()
{

}
void CameraWorker::Initialize()
{
    dataGray = new uchar[2464 * 2056];
    dateR = new uchar[2464 * 2056];
    dateG = new uchar[2464 * 2056];
    dateB = new uchar[2464 * 2056];
    // start vimb
    m_ApiController = new ApiController();
    VmbErrorType err = m_ApiController->StartUp();
    if (VmbErrorSuccess == err)
    {
        m_ApiController->OpenCameraF(m_cData.rStrCameraID);
        QObject::connect(m_ApiController->GetFrameObserver(), SIGNAL(FrameReceivedSignal(int)), this, SLOT(OnFrameReady(int)));
        m_nWidth = m_ApiController->GetWidth();
        m_nHeight = m_ApiController->GetHeight();
    }
    else
    {
        qDebug() << "Initialize Error" << QThread::currentThreadId();
        m_ApiController->CloseCamerF();
    }
}

void CameraWorker::start()
{
    m_ApiController->StartContinuousImageAcquisition();
}


void CameraWorker::stop()
{
    m_ApiController->StopContinuousImageAcquisition();
}

void CameraWorker::OnFrameReady(int status)
{

    // Pick up frame
    FramePtr pFrame = m_ApiController->GetFrame();
    VmbErrorType err = SP_ACCESS(pFrame)->GetImage(pBuffer);
    HalconCpp::HObject Hobj;
    if (VmbErrorSuccess == err)
    {
        switch (m_cData.m_nIndex)
        {
        case 1:case 2:
            memcpy(dataGray, pBuffer, m_nWidth * m_nHeight);
            HalconCpp::GenImage1(&Hobj, "byte", m_nWidth ,m_nHeight, (Hlong)(dataGray));
            break;
        case 3:case 4:
            for (int i = 0; i < m_nWidth * m_nHeight; i++)
            {
                dateR[i] = pBuffer[i * 3];
                dateG[i] = pBuffer[i * 3 + 1];
                dateB[i] = pBuffer[i * 3 + 2];
            }
            HalconCpp::GenImage3(&Hobj, "byte", m_nWidth ,m_nHeight, (Hlong)dateR, (Hlong)dateG, (Hlong)dateB);
            break;
        }
        m_cData.Hobj = Hobj;
        // start Alg
        emit sigAlgStart(m_cData);
    }
    m_ApiController->QueueFrame(pFrame);
}

